package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a04_组合总和3复习0
 * </p>
 *
 * @author flyduck
 * @since 2025/1/10
 */
public class a04_组合总和3复习0 {

    public static void main(String[] args) {
        a04_组合总和3复习0 test = new a04_组合总和3复习0();
        List<List<Integer>> lists = test.combinationSum3(9, 45);
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        traversal(result, path, k, n, 0, 1);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int targetCount,
                           int targetSum,
                           int sum,
                           int startIdx){
        //优化1：
        if (sum > targetSum) {
            return;
        }
        if (path.size() == targetCount) {
            if(sum == targetSum){
                result.add(new ArrayList<>(path));
            }
            return;
        }
        for (int i = startIdx; i <= 9 - (targetCount - path.size()) + 1; i++) {
            path.add(i);
            sum = sum + i;
            traversal(result, path, targetCount, targetSum,sum, i + 1);
            path.removeLast();
            sum = sum - i;
        }
    }
}
